//
//  MyProductionLineViewController.m
//  MagictoHire
//
//  Created by 锋 on 2017/12/11.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "MyProductionLineViewController.h"
#import "MyProductionLineTableViewCell.h"
#import "AddProductionLineViewController.h"
#import "ProductionLineModel.h"
#import "ProduceMachinesModel.h"
#import "ProduceMachineNameModel.h"
#import "ProduceLineDetailViewController.h"
#import "SetUpTimeViewController.h"

@interface MyProductionLineViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UITableView *myProductionLineTableView;
@property (nonatomic, strong) NSMutableArray *productionLineArr;
@property (nonatomic, assign) NSInteger page;
@end

@implementation MyProductionLineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _page = 0;
    self.productionLineArr = [NSMutableArray array];
    [self setupUI];
    [self setupMyProductionLineTableView];
    [self requsetProductionLine:_page];
    // Do any additional setup after loading the view.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self requsetProductionLine:_page];
}

- (void)setupUI {
    UIBarButtonItem *rightBtn = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"tianjia"] style:UIBarButtonItemStylePlain target:self action:@selector(addProductionLine)];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.rightBarButtonItem = rightBtn;
    self.navigationItem.title = @"我的产线";
    self.view.backgroundColor = RGB(242, 242, 242);
}

- (void)setupMyProductionLineTableView {
    _myProductionLineTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - STA_NAV_HEIGHT - SCREER_HeiX) style:UITableViewStyleGrouped];
    _myProductionLineTableView.delegate = self;
    _myProductionLineTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.000001)];
    view.backgroundColor = [UIColor whiteColor];
    _myProductionLineTableView.tableHeaderView = view;
    _myProductionLineTableView.tableFooterView = view;
    _myProductionLineTableView.backgroundColor = RGB(242, 242, 242);
    _myProductionLineTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myProductionLineTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewHeaderData)];
    self.myProductionLineTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreFootData)];
    self.myProductionLineTableView.mj_footer.automaticallyHidden = YES;
    if (@available(iOS 11.0, *)) {
        _myProductionLineTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    _myProductionLineTableView.estimatedRowHeight = 0;
    _myProductionLineTableView.estimatedSectionHeaderHeight = 0;
    _myProductionLineTableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:_myProductionLineTableView];
}

- (void)loadNewHeaderData {
    _page = 0;
    [self requsetProductionLine:_page];
}

- (void)loadMoreFootData {
    _page++;
    [self requsetProductionLine:_page];
}

- (void)requsetProductionLine:(NSInteger)page {
    WEAKSELF;
    NSDictionary *dic = @{@"page":[NSString stringWithFormat:@"%ld",page]};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestProductionLineParmers:dic Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [weakSelf.myProductionLineTableView.mj_header endRefreshing];
         [weakSelf.myProductionLineTableView.mj_footer endRefreshing];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             NSArray *tempArray = [ProductionLineModel mj_objectArrayWithKeyValuesArray:obj[@"data"][@"content"]];
             if (weakSelf.page == 0)
             {
                 [weakSelf.productionLineArr removeAllObjects];
             }
             [weakSelf.productionLineArr addObjectsFromArray:tempArray];
             [_myProductionLineTableView reloadData];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [weakSelf.myProductionLineTableView.mj_header endRefreshing];
         [weakSelf.myProductionLineTableView.mj_footer endRefreshing];
     }];
}

- (void)requestDeleteProductionLine:(NSString *)productionLineId {
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestDeleteProductionLineParmers:@{@"id":productionLineId} Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
//             [LTools showMBProgressWithText:@"提交成功" addToView:weakSelf.view];
             [weakSelf.myProductionLineTableView reloadData];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return _productionLineArr.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 128;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyProductionLineTableViewCell *cell = [[NSBundle mainBundle] loadNibNamed:@"MyProductionLineTableViewCell" owner:self options:nil].lastObject;
    cell.contentView.userInteractionEnabled = YES;
    cell.contentView.tag = indexPath.section;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    [cell.contentView addGestureRecognizer:longPress];
    cell.setBtn.tag = indexPath.section;
    [cell.setBtn addTarget:self action:@selector(onClickSetBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.checkDetailMessageBtn.tag = indexPath.section;
    [cell.checkDetailMessageBtn addTarget:self action:@selector(onClickCheckDetailMessageBtn:) forControlEvents:UIControlEventTouchUpInside];
    cell.layer.cornerRadius = 10;
    cell.layer.masksToBounds = YES;
    ProductionLineModel *productionModel = _productionLineArr[indexPath.section];
    ProduceKindModel *produceKindModel = productionModel.category;
    cell.produceLineNameLabel.text = productionModel.name;
    cell.produceLineKindLabel.text = produceKindModel.name;
    if (productionModel.free && [productionModel.free isEqual:@"1"] && ![productionModel.free isKindOfClass:[NSNull class]]) {
        cell.statusImageView.image = [UIImage imageNamed:@"xian"];
    } else if (productionModel.free && [productionModel.free isEqual:@"0"] && ![productionModel.free isKindOfClass:[NSNull class]]) {
        cell.statusImageView.image = [UIImage imageNamed:@"manyuan"];
    }
    cell.produceLinePointLabel.text = [NSString stringWithFormat:@"%ld个节点", [productionModel.galleryful integerValue]];
    NSArray *tempArr = productionModel.machines;
    NSString *nameStr = @"";
    for (int i = 0; i < tempArr.count; i++) {
        ProduceMachinesModel *model = tempArr[i];
        if (i == tempArr.count - 1) {
            nameStr = [NSString stringWithFormat:@"%@%@", nameStr, model.machine.name];
        } else {
            nameStr = [NSString stringWithFormat:@"%@%@、", nameStr, model.machine.name];
        }
    }
    nameStr = [NSString stringWithFormat:@"生产设备:%@", nameStr];
    cell.produceEquipmentLabel.text = nameStr;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    ProduceLineDetailViewController *produceLineDetailVC = [[ProduceLineDetailViewController alloc] init];
    ProductionLineModel *productionModel = _productionLineArr[indexPath.section];
    produceLineDetailVC.ID = productionModel.ID;
    produceLineDetailVC.produceLineType = MYPRODUCELINETYPE;
    [self.navigationController pushViewController:produceLineDetailVC animated:YES];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)longPress:(UILongPressGestureRecognizer *)recognizer {
    WEAKSELF;
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请选择" message:nil preferredStyle: UIAlertControllerStyleActionSheet];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * action) {
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
    }];
    
    UIAlertAction *saveAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * action) {
        ProductionLineModel *model = weakSelf.productionLineArr[recognizer.view.tag];
        [weakSelf.productionLineArr removeObjectAtIndex:recognizer.view.tag];
        [self requestDeleteProductionLine:model.ID];
    }];
    
    [alertController addAction:cancelAction];
    [alertController addAction:saveAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)addProductionLine {
    AddProductionLineViewController *addProductionLineVC = [[AddProductionLineViewController alloc] init];
    addProductionLineVC.produceType = ADDPRODUCETYPE;
    [self.navigationController pushViewController:addProductionLineVC animated:YES];
}

- (void)onClickCheckDetailMessageBtn:(UIButton *)sender {
    ProduceLineDetailViewController *produceLineDetailVC = [[ProduceLineDetailViewController alloc] init];
    ProductionLineModel *productionModel = _productionLineArr[sender.tag];
    produceLineDetailVC.ID = productionModel.ID;
    produceLineDetailVC.produceLineType = MYPRODUCELINETYPE;
    [self.navigationController pushViewController:produceLineDetailVC animated:YES];
}

- (void)onClickSetBtn:(UIButton *)sender {
    SetUpTimeViewController *vc = [[SetUpTimeViewController alloc] init];
    ProductionLineModel *productionModel = _productionLineArr[sender.tag];
    vc.ID = productionModel.ID;
    vc.setupTimeType = MYSETUPTIMETYPE;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
